<?php

namespace EasyTiktokSdk\Kernel;



use EasyTiktokSdk\Kernel\Contracts\Arrayable;
use EasyTiktokSdk\Kernel\Exceptions\RuntimeException;
use EasyTiktokSdk\Kernel\Support\Arr;
use EasyTiktokSdk\Kernel\Support\Collection;

/**
 * @param array|Collection|Arrayable|\ArrayAccess|\IteratorAggregate|\ArrayIterator|object $data
 * @param string $key
 * @param $default
 * @return array|mixed|null
 * @throws RuntimeException
 */
function data_get($data, $key, $default = null)
{
    switch (true) {
        case is_array($data):
            return Arr::get($data, $key, $default);
        case $data instanceof Collection:
            return $data->get($key, $default);
        case $data instanceof Arrayable:
            return Arr::get($data->toArray(), $key, $default);
        case $data instanceof \ArrayIterator:
            return $data->getArrayCopy()[$key] ? $data->getArrayCopy()[$key] : $default;
        case $data instanceof \ArrayAccess:
            return $data[$key] ? $data[$key] : $default;
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
            return $data->getIterator()->getArrayCopy()[$key] ? $data->getIterator()->getArrayCopy()[$key] : $default;
        case is_object($data):
            return $data->{$key} ? $data->{$key} : $default;
        default:
            throw new RuntimeException(sprintf('Can\'t access data with key "%s"', $key));
    }
}

/**
 * @param  array|Collection|Arrayable|\IteratorAggregate|\ArrayIterator $data
 * @return array
 * @throws RuntimeException
 */
function data_to_array($data)
{
    switch (true) {
        case is_array($data):
            return $data;
        case $data instanceof Collection:
            return $data->all();
        case $data instanceof Arrayable:
            return $data->toArray();
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
            return $data->getIterator()->getArrayCopy();
        case $data instanceof \ArrayIterator:
            return $data->getArrayCopy();
        default:
            throw new RuntimeException(sprintf('Can\'t transform data to array'));
    }
}

/**
 * @param int       $code
 * @param string    $msg
 * @param array     $data
 * @return array
 */
function get_ret_arr($code, $msg, $data = [])
{
    return [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
}